<template>
  <view class="viewpot">
    <wd-navbar
      fixed
      placeholder
      title="全部订单"
      left-arrow
      safeAreaInsetTop
      @click-left="handleClickLeft"
      :bordered="false"
    />
    <!-- Tabs 固定 -->
    <wd-tabs v-model="tabWithBadge" lineWidth="0" color="#00A140" @change="handleChange">
      <wd-tab
        v-for="(item, index) in tabsWithBadge"
        :key="index"
        :title="item.title"
        :badge-props="item.badgeProps"
      />
    </wd-tabs>

    <!-- 滚动列表 -->
    <scroll-view
      class="order-list"
      scroll-y
      refresher-enabled
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onPullDownRefresh"
      @scrolltolower="loadMoreOrders"
    >
      <view class="content">
        <view
          class="order-content"
          v-for="(order, idx) in filteredOrders(tabsWithBadge[tabWithBadge].title)"
          :key="idx"
        >
          <!-- 订单内容 -->
          <view class="dai-pay">
            <view class="dai-pay-left">
              <image src="@/static/prod/payimg.png" class="pay-img" mode="scaleToFill" />
            </view>
            <view class="dai-pay-center">
              <text class="day-pay-text">{{ order.name }}</text>
              <text class="day-pay-title">{{ order.desc }}</text>
              <text class="day-pay-price">￥{{ order.price }}</text>
            </view>
            <view class="dai-pay-right">
              <view class="dai-pay-rightTop">
                <text class="day-pay-title">{{ order.status }}</text>
              </view>
              <view class="dai-pay-rightBottom">
                <text>x{{ order.count }}</text>
              </view>
            </view>
          </view>

          <view class="dai-bottom">
            <view class="dai-bottom-right">
              <view
                v-for="(btn, bIndex) in order.buttons"
                :key="bIndex"
                :class="[btn.type === 'pay' ? 'pay-btn' : 'detele-btn']"
                @click="handleOrderAction(btn.label)"
              >
                {{ btn.label }}
              </view>
            </view>
          </view>
        </view>
        <!-- 加载更多状态 -->
        <view class="loading-more" v-if="isLoadingMore">
          <text>加载更多...</text>
        </view>

        <!-- 没有更多数据 -->
        <view class="no-more-data" v-if="!hasMore && !isLoadingMore">
          <text>没有更多的商品了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted } from 'vue'

  const tabWithBadge = ref(0)
  // badgeProps: { modelValue: 0, right: '-8px' }
  const tabsWithBadge = ref([
    { title: '全部' },
    { title: '待付款' },
    { title: '待发货' },
    { title: '待收货' },
    { title: '已完成' },
  ])

  const orders = ref<any[]>([])
  let pageNum = 1
  const pageSize = 7
  const refresherTriggered = ref(false)
  const isLoadingMore = ref(false)
  const hasMore = ref(true) // 是否还有更多数据

  function handleClickLeft() {
    uni.navigateBack()
  }

  const filteredOrders = (tabTitle: string) => {
    if (tabTitle === '全部') return orders.value
    return orders.value.filter((o) => o.status === tabTitle)
  }

  // 模拟请求数据
  function fetchOrders() {
    return new Promise<any[]>((resolve) => {
      setTimeout(() => {
        if (pageNum > 3) {
          // 模拟没有更多数据
          resolve([])
          return
        }

        const statusList = ['待付款', '待发货', '待收货', '已完成']

        const mockData = Array.from({ length: pageSize }, () => {
          const status = statusList[Math.floor(Math.random() * 4)]
          let buttons: { label: string; type: string }[] = []

          switch (status) {
            case '待付款':
              buttons = [
                { label: '取消订单', type: 'cancel' },
                { label: '继续付款', type: 'pay' },
              ]
              break
            case '待发货':
              buttons = [
                { label: '申请售后', type: 'cancel' },
                { label: '再来一单', type: 'cancel' },
              ]
              break
            case '待收货':
              buttons = [
                { label: '查看物流', type: 'cancel' },
                { label: '申请售后', type: 'cancel' },
                { label: '确认收货', type: 'pay' },
              ]
              break
            case '已完成':
              buttons = [
                { label: '查看物流', type: 'cancel' },
                { label: '再来一单', type: 'cancel' },
              ]
              break
          }

          return {
            name: '敬修堂防脱滋养育发洗发露',
            desc: '控油防脱两不误 细腻丰富泡沫',
            price: 199,
            count: 1,
            status,
            buttons,
          }
        })

        resolve(mockData)
      }, 800)
    })
  }

  // 加载数据
  async function loadOrders(reset = false) {
    if (reset) {
      pageNum = 1
      orders.value = []
      hasMore.value = true
    }

    isLoadingMore.value = true
    const newData = await fetchOrders()
    if (newData.length < pageSize) {
      hasMore.value = false
    }
    orders.value = [...orders.value, ...newData]
    // updateTabBadge()
    isLoadingMore.value = false
  }

  // 更新角标
  function updateTabBadge() {
    tabsWithBadge.value.forEach((tab) => {
      // if (tab.title === '全部') {
      //   tab.badgeProps.modelValue = orders.value.length
      // } else {
      //   tab.badgeProps.modelValue = orders.value.filter((o) => o.status === tab.title).length
      // }
    })
  }

  // 下拉刷新
  function onPullDownRefresh() {
    refresherTriggered.value = true
    loadOrders(true).then(() => {
      refresherTriggered.value = false
    })
  }

  // 触底加载
  function loadMoreOrders() {
    if (!hasMore.value || isLoadingMore.value) return
    pageNum++
    loadOrders()
  }

  function handleOrderAction(type: string) {
    if (type === '继续付款') {
      uni.showToast({
        title: '已支付',
        icon: 'none',
      })
    }
    if (type === '再来一单') {
      uni.showToast({
        title: '再来一单',
        icon: 'none',
      })
    }
    if (type === '申请售后') {
      uni.showToast({
        title: '申请售后',
        icon: 'none',
      })
    }
    if (type === '确认收货') {
      uni.showToast({
        title: '确认收货',
        icon: 'none',
      })
    }
    if (type === '查看物流') {
      uni.showToast({
        title: '查看物流',
        icon: 'none',
      })
    }
    if (type === '取消订单') {
      uni.showToast({
        title: '取消订单',
        icon: 'none',
      })
    }
  }

  function handleChange(e: { index: number; name: string }) {
    console.log('切换标签', e)
    tabWithBadge.value = e.index
    // 切换标签时重置分页
    pageNum = 1
    hasMore.value = true
    orders.value = []
    loadOrders()
  }

  onMounted(() => {
    loadOrders()
  })
  onLoad((options: any) => {
    if (options.tab) {
      const tabName = decodeURIComponent(options.tab)
      const index = tabsWithBadge.value.findIndex((t) => t.title === tabName)
      if (index !== -1) {
        tabWithBadge.value = index
      }
    }
  })
</script>

<style lang="scss">
  page {
    overflow: hidden;
    background: #f5f5f5;
  }

  .order-list {
    height: 1400rpx;
  }
  .content {
    background: #f5f5f5;
    .order-content {
      margin: 10rpx 40rpx;
      height: 272rpx;
      border-radius: 10px;
      background-color: #fff;
      margin-bottom: 20rpx;
      .dai-pay {
        margin: 0 20rpx;
        display: flex;
        height: 160rpx;
        .dai-pay-left {
          flex: 1.5;
          display: flex;
          justify-content: center;
          align-items: center;
          .pay-img {
            height: 140rpx;
            width: 140rpx;
            border-radius: 12rpx;
          }
        }
        .dai-pay-center {
          flex: 3;
          display: flex;
          flex-direction: column;
          .day-pay-text {
            margin-top: 20rpx;
            font-size: 24rpx;
            font-weight: 700;
            letter-spacing: 0px;
            line-height: 19.6px;
            color: rgba(26, 26, 26, 1);
            text-align: left;
          }
          .day-pay-title {
            font-size: 20rpx;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 16.8px;
            color: rgba(153, 153, 153, 1);
            text-align: left;
          }
          .day-pay-price {
            margin-top: 20rpx;
            font-size: 24rpx;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 17.58px;
            color: rgba(26, 26, 26, 1);
            text-align: left;
          }
        }
        .dai-pay-right {
          flex: 1;
          display: flex;
          flex-direction: column;
          .dai-pay-rightTop {
            flex: 1;
            display: flex;
            justify-content: center;
            padding: 10rpx 0 0 0;
          }
          .dai-pay-rightBottom {
            flex: 1;
            padding: 30rpx 0 20rpx 0;
            display: flex;
            font-size: 18rpx;
            justify-items: center;
            justify-content: center;
            color: rgba(153, 153, 153, 1);
          }
        }
      }
      .dai-bottom {
        display: flex;
        margin: 0 20rpx;
        justify-content: space-between;
        height: 112rpx;
        .dai-bottom-right {
          display: flex;
          margin-left: auto;
          padding: 20rpx 0;
          .detele-btn,
          .pay-btn {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 154rpx;
            height: 54rpx;
            border-radius: 24rpx;
            font-size: 28rpx;
            margin-left: 30rpx;
          }
          .detele-btn {
            border: 1px solid rgba(204, 204, 204, 1);
          }
          .pay-btn {
            color: #fff;
            background: rgba(0, 161, 64, 1);
          }
        }
      }
    }
  }
  .day-pay-title {
    font-size: 24rpx;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 16.8px;
    color: rgba(153, 153, 153, 1);
    text-align: left;
  }
  .loading-more {
    text-align: center;
    padding: 30rpx 0;
    font-size: 28rpx;
    color: #999;
  }

  .no-more-data {
    text-align: center;
    padding: 30rpx 0;
    font-size: 28rpx;
    color: #ccc;
  }
</style>
